<?php

namespace addons\modules\controllers;

use models\SysUsers;
use system\Base;
use system\MyError;
use system\Tool\DataBase;

class Index extends Base {
    // 运行的模块名
    protected $name = '';
    // 运行的SQL地址
    protected $config = '';
    // 锁定的信息后缀
    protected $lock = '.lock';
    // 运行的sql后缀
    protected $sql = '.php';

    /**
     * 初始化方法
     * @author Colin<amcolin@126.com>
     */
    public function __construct() {
        parent::__construct();
        $this->name   = values('get.name');
        $this->config = dirname(__DIR__) . '/sql/shop.php';
        $this->lock   = $this->config . $this->lock;
        $this->sql    = $this->config . $this->sql;
    }

    /**
     * 安装方法
     * @author Colin<amcolin@126.com>
     * @throws
     */
    public function index() {
		if ($this->isInstall()) {
			return error('你已经安装过该系统了');
		}
		if (self::$is_post){
			$content = file_get_contents(Common . '/.env');
			$db = self::$post['db'];
			foreach ($db as $key => $val){
				$content = preg_replace_callback('/(DB_' . strtoupper($key) . '=)[\w\.\_\-\s]+/' , function ($call) use ($val){
					return $call[1] . $val;
				} , $content);
			}
			file_put_contents(Common . '/.env' , $content);
			// 找到数据库文件，开始导入数据库
			$config = include $this->config;
			$this->executeSql($config);
			$admin = self::$post['admin'];
			$sysUser = new SysUsers();
			$sysUser->register($admin['account'] , $admin['pass'] , 'Supper Master');
			file_put_contents($this->lock, time());
			return success('安装成功');
		}
		$config = [
			'db' => [
				'host' => '127.0.0.1' ,
				'port' => '3306' ,
				'user' => 'root' ,
				'pass' => '' ,
				'name' => 'myclassphp-shop' ,
				'prefix' => 'mc_' ,
			] ,
			'admin' => [
				'site' => 'http://shopadmin.myclassphp.com' ,
				'account' => 'admin' ,
				'pass' => 'admin' ,
			]
		];
		self::assign('config' , $config);
		return self::view('index');
    }

    /**
     * 是否安装
     * @return bool
     */
    protected function isInstall() {
        if ($this->lock && is_file($this->lock)) {
            return true;
        }

        return false;
    }

    /**
     * 执行SQL语句
     *
     * @param array  $config
     *
     * @throws
     */
    protected function executeSql($config) {
        $tool = new DataBase();
        $db   = $tool->getDB();
        $db->startTransaction();
        try {
            // 把所有的语句都执行一遍
            foreach ($config as $key => $value) {
				foreach ($value as $k => $v) {
					$v && $v = $this->parseTableName($v);
					if ($v && $tool->execute($v) < 1) {
						$db->rollback();
						throw new MyError('SQL语句执行错误 [' . $v . ']');
					}
				}
            }
            $db->commit();
        } catch (MyError $e) {
            $db->rollback();
            E($e->getMessage());
        }
    }

    /**
     * 解析表名
     *
     * @param string $sql
     *
     * @return mixed
     */
    protected function parseTableName($sql = '') {
        $prefix = Config('DB_PREFIX');

        return str_replace('@', $prefix ?: '', $sql);
    }
}
